package com.fengmoxi.ctv.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.FragmentActivity;
import androidx.leanback.app.BackgroundManager;
import androidx.leanback.app.BrowseSupportFragment;
import androidx.leanback.widget.ArrayObjectAdapter;
import androidx.leanback.widget.HeaderItem;
import androidx.leanback.widget.ListRow;
import androidx.leanback.widget.ListRowPresenter;
import androidx.leanback.widget.OnItemViewClickedListener;
import androidx.leanback.widget.OnItemViewSelectedListener;
import androidx.leanback.widget.Presenter;
import androidx.leanback.widget.Row;
import androidx.leanback.widget.RowPresenter;

import com.fengmoxi.ctv.R;
import com.fengmoxi.ctv.activity.config.lamp.ConfigLampActivity;
import com.fengmoxi.ctv.manage.AppDataManage;
import com.fengmoxi.ctv.manage.HdmiInCheckManage;
import com.fengmoxi.ctv.manage.HomeButtonReceiver;
import com.fengmoxi.ctv.manage.NetworkUtils;
import com.fengmoxi.ctv.model.AppModel;
import com.fengmoxi.ctv.model.ConfigModel;
import com.fengmoxi.ctv.presenter.AppCardPresenter;
import com.fengmoxi.ctv.presenter.ConfigCardPresenter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends FragmentActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private BrowseSupportFragment mBrowseFragment;
    private ArrayObjectAdapter rowsAdapter;
    private Context mContext;
    private HomeButtonReceiver mHomeButtonReceiver;
    private TextView mTimeTextView;
    private ImageView mNetworkStatusImageView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = this;
        mTimeTextView = findViewById(R.id.time);
        mNetworkStatusImageView = findViewById(R.id.network_status);
        mBrowseFragment = (BrowseSupportFragment) getSupportFragmentManager().findFragmentById(R.id.main_browse_fragment);

        BackgroundManager mBackgroundManager = BackgroundManager.getInstance(this);
        mBackgroundManager.attach(getWindow());
        DisplayMetrics mMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(mMetrics);

        assert mBrowseFragment != null;
        mBrowseFragment.setHeadersState(BrowseSupportFragment.HEADERS_DISABLED);
        mBrowseFragment.setTitleView(null);
        Timer timer = new Timer();
        timer.schedule(new TimeRefreshTask(), 0, 1000);

        setupRowsAdapter();

        if (new HdmiInCheckManage().getState()) {
            Intent i = new Intent(this, CameraActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
        }

        mHomeButtonReceiver = new HomeButtonReceiver(this, new HomeButtonReceiver.OnHomeBtnPressListener() {
            @Override
            public void onHomeBtnPress() {
                mBrowseFragment.setSelectedPosition(0);
            }

            @Override
            public void onHomeBtnLongPress() {

            }
        });
        mHomeButtonReceiver.start();
    }

    @Override
    protected void onDestroy() {
        mHomeButtonReceiver.stop();
        super.onDestroy();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mBrowseFragment.setSelectedPosition(0);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private class TimeRefreshTask extends TimerTask {
        @Override
        public void run() {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
            Date date = new Date(System.currentTimeMillis());
            MainActivity.this.runOnUiThread(() -> {
                // 刷新时间
                mTimeTextView.setText(simpleDateFormat.format(date));
                if (NetworkUtils.isEthernetNetwork(mContext)) {
                    mNetworkStatusImageView.setImageResource(R.drawable.ic_ethernet);
                    mNetworkStatusImageView.setVisibility(View.VISIBLE);
                } else if (NetworkUtils.isWifiNetwork(mContext)) {
                    switch (NetworkUtils.getWifiSignalLevel(mContext)) {
                        case 1:
                            mNetworkStatusImageView.setImageResource(R.drawable.ic_wifi_1);
                            break;
                        case 2:
                            mNetworkStatusImageView.setImageResource(R.drawable.ic_wifi_2);
                            break;
                        case 3:
                            mNetworkStatusImageView.setImageResource(R.drawable.ic_wifi_3);
                            break;
                        default:
                            mNetworkStatusImageView.setImageResource(R.drawable.ic_wifi_0);
                            break;
                    }
                    mNetworkStatusImageView.setVisibility(View.VISIBLE);
                } else {
                    mNetworkStatusImageView.setVisibility(View.GONE);
                }
            });
        }
    }

    private void setupRowsAdapter() {
        rowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
        setPhotoRows();// 照片行
        setVideoRows(); // 视频行
        setAppRows();// 应用行
        setConfigRows();// 配置行
        mBrowseFragment.setAdapter(rowsAdapter);
        mBrowseFragment.setOnItemViewClickedListener(new ItemViewClickedListener());
        mBrowseFragment.setOnItemViewSelectedListener(new ItemViewSelectedListener());
    }

    private void setPhotoRows() {

    }

    private void setVideoRows() {

    }

    private void setAppRows() {
        AppCardPresenter mAppCardPresenter = new AppCardPresenter();
        ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(mAppCardPresenter);
        List<AppModel> appDataList = new AppDataManage(mContext).getLaunchAppList();
        int cardCount = appDataList.size();
        for (int i = 0; i < cardCount; i++) {
            listRowAdapter.add(appDataList.get(i));
        }
        HeaderItem header = new HeaderItem(0, getResources().getString(R.string.app_header_app));
        rowsAdapter.add(new ListRow(header, listRowAdapter));
    }

    private void setConfigRows() {
        ConfigCardPresenter mConfigPresenter = new ConfigCardPresenter();
        ArrayObjectAdapter configRowAdapter = new ArrayObjectAdapter(mConfigPresenter);
        configRowAdapter.add(new ConfigModel(0, R.drawable.ic_config_hdmi_in, getResources().getString(R.string.app_item_config_hdmi_in)));
        configRowAdapter.add(new ConfigModel(1, R.drawable.ic_config_lamp, getResources().getString(R.string.app_item_config_lamp)));
        configRowAdapter.add(new ConfigModel(2, R.drawable.ic_config_network, getResources().getString(R.string.app_item_config_network)));
        configRowAdapter.add(new ConfigModel(3, R.drawable.ic_config_application, getResources().getString(R.string.app_item_config_application)));
        configRowAdapter.add(new ConfigModel(99, R.drawable.ic_config_sys, getResources().getString(R.string.app_item_config_sys)));
        HeaderItem header = new HeaderItem(0, getResources().getString(R.string.app_header_config));
        rowsAdapter.add(new ListRow(header, configRowAdapter));
    }

    private final class ItemViewClickedListener implements OnItemViewClickedListener {
        @Override
        public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
            if (item instanceof AppModel) {
                AppModel appBean = (AppModel) item;
                Log.d(TAG, "Click App Item: " + appBean.getName() + "[" + appBean.getPackageName() + "]");
                Intent launchIntent = mContext.getPackageManager().getLaunchIntentForPackage(
                        appBean.getPackageName());
                if (launchIntent != null) {
                    mContext.startActivity(launchIntent);
                }
            } else if (item instanceof ConfigModel) {
                switch (((ConfigModel) item).getId()) {
                    case 99:
                        Log.d(TAG, "Click Config Item: sys");
                        startActivity(new Intent(Settings.ACTION_SETTINGS));
                        break;
                    case 0:
                        Log.d(TAG, "Click Config Item: hdmi in");
                        startActivity(new Intent(MainActivity.this, CameraActivity.class));
                        break;
                    case 1:
                        Log.d(TAG, "Click Config Item: lamp");
                        startActivity(new Intent(MainActivity.this, ConfigLampActivity.class));
                        break;
                    case 2:
                        Log.d(TAG, "Click Config Item: network");
                        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                        break;
                    case 3:
                        Log.d(TAG, "Click Config Item: application");
                        startActivity(new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS));
                        break;
                }
            }
        }
    }

    private static final class ItemViewSelectedListener implements OnItemViewSelectedListener {
        @Override
        public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
//            if (item instanceof Movie) {
//                mBackgroundUri = ((Movie) item).getBackgroundImageUrl();
//                startBackgroundTimer();
//            }
        }
    }
}